package com.example.wy_homework6;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private EditText etUrl;
    private Button btnGo, btnBack, btnForward, btnHistory;
    private ListView lvHistory;

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private ArrayList<String> historyList = new ArrayList<>();
    private ArrayAdapter<String> historyAdapter;
    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 启用进度条功能
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.activity_main);

        // 初始化视图
        initViews();

        // 初始化WebView
        initWebView();

        // 初始化历史记录
        initHistory();

        // 设置按钮点击事件
        setupButtonListeners();
    }

    private void initViews() {
        webView = findViewById(R.id.webView);
        etUrl = findViewById(R.id.etUrl);
        btnGo = findViewById(R.id.btnGo);
        btnBack = findViewById(R.id.btnBack);
        btnForward = findViewById(R.id.btnForward);
        btnHistory = findViewById(R.id.btnHistory);
        lvHistory = findViewById(R.id.lvHistory);
    }

    private void initWebView() {
        // 启用JavaScript
        webView.getSettings().setJavaScriptEnabled(true);

        // 设置WebChromeClient，用于处理进度条等
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // 设置进度条
                getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100);
            }
        });

        // 设置WebViewClient，使链接在当前WebView中打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                etUrl.setText(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
    }

    private void initHistory() {
        sharedPreferences = getSharedPreferences("WebViewBrowserHistory", MODE_PRIVATE);
        editor = sharedPreferences.edit();

        while (!sharedPreferences.getString("url_" + i, "").isEmpty()) {
            historyList.add(sharedPreferences.getString("url_" + i, ""));
            i += 1;
        }

        historyAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, historyList);
        lvHistory.setAdapter(historyAdapter);

        // 历史记录点击事件
        lvHistory.setOnItemClickListener((parent, view, position, id) -> {
            String url = historyList.get(position);
            webView.loadUrl(url);
            etUrl.setText(url);
            lvHistory.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
        });
    }

    private void setupButtonListeners() {
        // GO按钮点击事件
        btnGo.setOnClickListener(v -> {
            String url = etUrl.getText().toString().trim();

            if (android.webkit.URLUtil.isNetworkUrl(url)) {
                webView.loadUrl(url);
                lvHistory.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                // 页面加载完成，添加到历史记录
                if (!historyList.contains(url)) {
                    historyList.add(url);
                    editor.putString("url_" + i, url).apply();
                    i += 1;
                }
            } else {
                Toast.makeText(MainActivity.this, "网址格式不正确，请重新输入", Toast.LENGTH_SHORT).show();
                etUrl.requestFocus();
            }
        });

        // 后退按钮点击事件
        btnBack.setOnClickListener(v -> {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                Toast.makeText(MainActivity.this, "无法后退", Toast.LENGTH_SHORT).show();
            }
        });

        // 前进按钮点击事件
        btnForward.setOnClickListener(v -> {
            if (webView.canGoForward()) {
                webView.goForward();
            } else {
                Toast.makeText(MainActivity.this,
                        "无法前进", Toast.LENGTH_SHORT).show();
            }
        });

        // 历史按钮点击事件
        btnHistory.setOnClickListener(v -> {
            if (webView.getVisibility() == View.VISIBLE) {
                webView.setVisibility(View.GONE);
                lvHistory.setVisibility(View.VISIBLE);
            } else {
                webView.setVisibility(View.VISIBLE);
                lvHistory.setVisibility(View.GONE);
            }
        });
    }
}